package com.formiaomiao.demain.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.formiaomiao.demain.R;
import com.formiaomiao.demain.adapter.DemainCommentAdapter;
import com.formiaomiao.demain.base.BaseActivity;
import com.formiaomiao.demain.base.BaseUrl;
import com.formiaomiao.demain.model.DemainCommentBean;
import com.formiaomiao.demain.ui.PublishWindow;
import com.formiaomiao.demain.util.DateUtils;
import com.formiaomiao.demain.util.MessageEvent;
import com.formiaomiao.demain.util.PreferenceUtils;
import com.formiaomiao.demain.util.PreferenceValues;
import com.formiaomiao.demain.util.StaticValues;
import com.formiaomiao.demain.util.ToastUtils;
import com.formiaomiao.demain.util.UseGlideUtils;
import com.formiaomiao.demain.weight.LoadingDialog;
import com.lzy.ninegrid.ImageInfo;
import com.lzy.ninegrid.NineGridView;
import com.lzy.ninegrid.preview.NineGridViewClickAdapter;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sharesdk.onekeyshare.OnekeyShare;

public class DemainCommentActivity extends BaseActivity implements DemainCommentAdapter.setViewClickListener {

    @BindView(R.id.iv_class_back)
    ImageView ivClassBack;
    @BindView(R.id.tv_class_name)
    TextView tvClassName;
    @BindView(R.id.tv_class_submit)
    TextView tvClassSubmit;
    @BindView(R.id.storeHouseHeader)
    MaterialHeader storeHouseHeader;
    @BindView(R.id.iv_userhead)
    ImageView ivUserhead;
    @BindView(R.id.tv_username)
    TextView tvUsername;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.tv_content)
    TextView tvContent;
    @BindView(R.id.ng_imgs)
    NineGridView ngImgs;
    @BindView(R.id.rv_comment)
    RecyclerView rvComment;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.ll_share)
    LinearLayout llShare;
    @BindView(R.id.ll_msg)
    LinearLayout llMsg;

    ArrayList<ImageInfo> imageInfo = new ArrayList<>();
    DemainCommentAdapter adapter;
    List<DemainCommentBean.DataBean.ListBean> list = new ArrayList<>();
    DemainCommentBean demainCommentBean = new DemainCommentBean();

    PublishWindow publishWindow;
    PopupWindow pop;

    LoadingDialog dialog;

    String topicid;
    int page = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_demain_comment);
        ButterKnife.bind(this);
        ViewInit();
    }

    private void ViewInit() {
        dialog = new LoadingDialog(this);
        tvClassName.setText("动态详情");
        pop = new PopupWindow(this);
        publishWindow = new PublishWindow(this, pop);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        rvComment.setLayoutManager(manager);
        adapter = new DemainCommentAdapter(this, list, getIntent().getIntExtra("userid", 0));
        rvComment.setAdapter(adapter);
        adapter.setOnViewClickListener(this);
        topicid = getIntent().getStringExtra("demainid");
        UseGlideUtils.setGlide(this, getIntent().getStringExtra("head"), ivUserhead);
        tvUsername.setText(getIntent().getStringExtra("name"));
        tvTime.setText(DateUtils.timess(Long.parseLong(getIntent().getStringExtra("time"))));
        tvContent.setText(getIntent().getStringExtra("data"));
        for (int i = 0; i < getIntent().getStringArrayListExtra("imgs").size(); i++) {
            ImageInfo info = new ImageInfo();
            info.setBigImageUrl(getIntent().getStringArrayListExtra("imgs").get(i));
            info.setThumbnailUrl(getIntent().getStringArrayListExtra("imgs").get(i));
            imageInfo.add(info);
        }
        ngImgs.setAdapter(new NineGridViewClickAdapter(this, imageInfo));
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                DataInit(++page);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                DataInit(page);
            }
        });
        DataInit(1);
    }

    @OnClick({R.id.iv_class_back, R.id.iv_userhead, R.id.tv_username, R.id.ll_share, R.id.ll_msg})
    public void onViewClicked(View view) {
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.iv_class_back:
                finish();
                break;
            case R.id.iv_userhead:
                intent.setClass(this, DemainUserActivity.class);
                intent.putExtra("id", getIntent().getIntExtra("id", 0));
                intent.putExtra("name", getIntent().getStringExtra("name"));
                intent.putExtra("head", getIntent().getStringExtra("head"));
                startActivity(intent);
                break;
            case R.id.tv_username:
                intent.setClass(this, DemainUserActivity.class);
                intent.putExtra("id", getIntent().getIntExtra("id", 0));
                intent.putExtra("name", getIntent().getStringExtra("name"));
                intent.putExtra("head", getIntent().getStringExtra("head"));
                startActivity(intent);
                break;
            case R.id.ll_share:
                showShare();
                break;
            case R.id.ll_msg:
                publishWindow.showPicPopWindow(rvComment);
                publishWindow.setOnPublishClickListener(new PublishWindow.PublishClickListener() {
                    @Override
                    public void onPublishClickListener(View v, String data) {
                        PublishDataInit(topicid, data);
                    }
                });
                break;
        }
    }

    private void showShare() {
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
        // title标题，微信、QQ和QQ空间等平台使用
        oks.setTitle("Demain");
        // text是分享文本，所有平台都需要这个字段
        oks.setText(getIntent().getStringExtra("data"));
        oks.setImageUrl("https://www.bmob.cn/uploads/attached/app/logo/20180711/9ede3748-9162-09e3-6b97-10c6a39565fc.png");
        // url在微信、微博，Facebook等平台中使用
        oks.setUrl("http://demain.bmob.site/");
        // 启动分享GUI
        oks.show(this);
    }

    private void DataInit(final int pageNum) {
        if (pageNum == 1) {
            dialog.show();
        }
        HttpParams params = new HttpParams();
        params.put("topicid", topicid);
        params.put("pageNum", pageNum);
        params.put("pageSize", 20);
        OkGo.<String>post(BaseUrl.SELECTCOMMENT)
                .headers("Authorization", PreferenceUtils.getString(this, PreferenceValues.TOKEN))
                .params(params).tag(this).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                if (response.body().contains("200")) {
                    if (pageNum == 1) {
                        list.clear();
                    }
                    demainCommentBean = gson.fromJson(response.body(), DemainCommentBean.class);
                    list.addAll(demainCommentBean.getData().getList());
                    adapter.notifyDataSetChanged();
                } else {
                    ToastUtils.show(DemainCommentActivity.this, demainCommentBean.getMsg());
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
            }

            @Override
            public void onFinish() {
                super.onFinish();
                dialog.dismiss();
                refreshLayout.finishRefresh();
                refreshLayout.finishLoadMore();
            }
        });
    }

    /**
     * 评论动态
     *
     * @param topicid
     * @param data
     */
    private void PublishDataInit(String topicid, String data) {
        dialog.show();
        HttpParams params = new HttpParams();
        params.put("topicid", topicid);
        params.put("content", data);
        params.put("fromuid", StaticValues.userid);
        OkGo.<String>post(BaseUrl.INSERTCOMMENT)
                .headers("Authorization", PreferenceUtils.getString(DemainCommentActivity.this, PreferenceValues.TOKEN))
                .params(params).tag(this).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                if (response.body().contains("200")) {
                    ToastUtils.show(DemainCommentActivity.this, "评论成功");
                    EventBus.getDefault().post(new MessageEvent("上传数据"));
                    DataInit(1);
                    if (pop != null) {
                        pop.dismiss();
                    }
                } else {
                    ToastUtils.show(DemainCommentActivity.this, "评论失败");
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
            }

            @Override
            public void onFinish() {
                dialog.dismiss();
            }
        });
    }

    /**
     * 评论评论
     *
     * @param i
     * @param discussdata
     */
    private void DiscussCommentData(int i, String discussdata) {
        dialog.show();
        HttpParams params = new HttpParams();
        params.put("comid", list.get(i).getComid());
        params.put("discussdata", discussdata);
        params.put("fromid", StaticValues.userid);
        OkGo.<String>post(BaseUrl.INSERTDISCUSS)
                .headers("Authorization", PreferenceUtils.getString(DemainCommentActivity.this, PreferenceValues.TOKEN))
                .params(params).tag(this).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                if (response.body().contains("200")) {
                    ToastUtils.show(DemainCommentActivity.this, "评论成功");
                    DataInit(1);
                    if (pop != null) {
                        pop.dismiss();
                    }
                } else {
                    ToastUtils.show(DemainCommentActivity.this, "评论失败");
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
            }

            @Override
            public void onFinish() {
                super.onFinish();
                dialog.dismiss();
            }
        });
    }

    /**
     * 删除动态评论
     *
     * @param i
     * @param dialogInterface
     */
    private void DeleteCommentData(final int i, final DialogInterface dialogInterface) {
        dialog.show();
        HttpParams params = new HttpParams();
        params.put("comid", list.get(i).getComid());
        OkGo.<String>post(BaseUrl.DELETECOMMENT)
                .headers("Authorization", PreferenceUtils.getString(DemainCommentActivity.this, PreferenceValues.TOKEN))
                .params(params).tag(this).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                if (response.body().contains("200")) {
                    EventBus.getDefault().post(new MessageEvent("上传数据"));
                    ToastUtils.show(DemainCommentActivity.this, "删除成功");
                    list.remove(i);
                    adapter.notifyDataSetChanged();
                    dialogInterface.dismiss();
                } else {
                    ToastUtils.show(DemainCommentActivity.this, "删除失败");
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
            }

            @Override
            public void onFinish() {
                super.onFinish();
                dialog.dismiss();
            }
        });
    }

    @Override
    public void deletelistener(View v, final int i) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setMessage("是否删除?");
        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });
        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int x) {
                DeleteCommentData(i, dialogInterface);
            }
        });
        dialog.show();
    }

    @Override
    public void checkdiscusslistener(View v, int i) {
        Intent intent = new Intent();
        intent.setClass(this, DiscussCommentActivity.class);
        intent.putExtra("id", list.get(i).getComid());
        intent.putExtra("userid", list.get(i).getUserBean().getId());
        intent.putExtra("username", list.get(i).getUserBean().getNickName());
        intent.putExtra("userhead", list.get(i).getUserBean().getUserHead());
        intent.putExtra("nickname", list.get(i).getUserBean().getNickName());
        intent.putExtra("data", list.get(i).getContent());
        intent.putExtra("time", list.get(i).getCreateDate());
        startActivity(intent);
    }

    @Override
    public void publishlistener(View v, final int i) {
        publishWindow.showPicPopWindow(rvComment);
        publishWindow.setOnPublishClickListener(new PublishWindow.PublishClickListener() {
            @Override
            public void onPublishClickListener(View v, String data) {
                DiscussCommentData(i, data);
            }
        });
    }

    @Override
    public void headItemlistener(View v, int i) {
        Intent intent = new Intent();
        intent.setClass(DemainCommentActivity.this, DemainUserActivity.class);
        intent.putExtra("id", list.get(i).getUserBean().getId());
        intent.putExtra("name", list.get(i).getUserBean().getNickName());
        intent.putExtra("head", list.get(i).getUserBean().getUserHead());
        intent.putExtra("username", list.get(i).getUserBean().getNickName());
        startActivity(intent);
    }
}
